var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
import { existsSync, renameSync } from 'fs';
import path from 'path';
import { removeFileExtension, getPagePaths, addLeadingSlash } from '../prebuild.js';
import renameInternalLinksInPage from './renameInternalLinksInPage.js';
/**
 * Renames a link in the file system. If the link is a directory, all links within the directory will be renamed as well.
 * @param oldFilePath - The existing directory or file to rename
 * @param newFilePath - The new directory or file name
 * @param force
 */
export const renameFilesAndUpdateLinksInContent = (oldFilePathString, newFilePathString, force = false) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, e_1, _b, _c;
    const oldFilePath = path.parse(path.normalize(oldFilePathString));
    const newFilePath = path.parse(path.normalize(newFilePathString));
    if (oldFilePath.dir === newFilePath.dir && oldFilePath.base === newFilePath.base) {
        throw new Error('The old and new file paths are the same.');
    }
    else if (oldFilePath.ext !== newFilePath.ext) {
        if (force) {
            console.log('Warning: the file extensions are not the same.');
        }
        else {
            throw new Error('The file extensions are not the same. Use the --force flag to override.');
        }
    }
    // if the file or directory hasn't already been manually renamed, rename it
    if (existsSync(oldFilePathString)) {
        if (!force && existsSync(newFilePathString)) {
            throw new Error('The new file path already exists. Use the --force flag to overwrite it.');
        }
        renameSync(oldFilePathString, newFilePathString);
        console.log(`Renamed ${oldFilePathString} to ${newFilePathString}`);
    }
    else if (!force) {
        throw new Error('The old file path does not exist. Use the --force flag to skip the file system renaming.');
    }
    const oldLink = addLeadingSlash(removeFileExtension(oldFilePath));
    const newLink = addLeadingSlash(removeFileExtension(newFilePath));
    const pagesInDirectory = getPagePaths(process.cwd());
    const renameLinkPromises = [];
    try {
        for (var _d = true, pagesInDirectory_1 = __asyncValues(pagesInDirectory), pagesInDirectory_1_1; pagesInDirectory_1_1 = yield pagesInDirectory_1.next(), _a = pagesInDirectory_1_1.done, !_a; _d = true) {
            _c = pagesInDirectory_1_1.value;
            _d = false;
            const filePath = _c;
            renameLinkPromises.push((() => __awaiter(void 0, void 0, void 0, function* () {
                const numRenamedLinks = yield renameInternalLinksInPage(path.join(process.cwd(), filePath), oldLink, newLink);
                if (numRenamedLinks > 0) {
                    console.log(`Renamed ${numRenamedLinks} link(s) in ${filePath}`);
                }
            }))());
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (!_d && !_a && (_b = pagesInDirectory_1.return)) yield _b.call(pagesInDirectory_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    yield Promise.all(renameLinkPromises);
    return;
});
// renameFilesAndUpdateLinksInContent('/test/A.mdx', '/test/hello.mdx');
